﻿using System;
using System.Data;
using System.Text;
using System.Configuration;
using System.Globalization;

namespace BizElements.Core.ProviderComponents
{
    /// <summary>Renders CONTAINS predicate as compatible LIKE predicate.</summary>
    sealed class ContainsAsLikePredicateRenderer : IContainsPredicateRenderer
    {
        #region Render as LIKE predicate.

        /// <summary>Renders CONTAINS predicate as compatible LIKE predicate.</summary>
        /// <param name="contains">Contains predicate.</param>
        /// <param name="dbms">Target DBMS.</param>
        /// <param name="output">StringBuilder to which SQL is appended.</param>
        /// <param name="parameters">SQL parameter collection to which the object's and its children's
        /// parameters are added. After the rendering is done the collection contains all parameters with unique names.</param>
        public void Render(ContainsPredicate contains, DbmsType dbms, StringBuilder output, DbParameterCollection parameters)
        {
            output.Append("(");
            contains.PredicateItems[0].Render(dbms, output, parameters);
            if (contains.Negate)
                output.Append(" NOT LIKE ");
            else
                output.Append(" LIKE ");

            IDbColumn field = (IDbColumn)contains.PredicateItems[0].Item;
            string pattern = (string)(contains.PredicateItems[1].Item as DbParameter).Value;
            pattern = "%" + pattern + "%";

            PredicateItem parametrizedPattern = new PredicateItem(pattern, DbType.String, field.MaxLengthIfText, field.GetPrefixedAlias());
            parametrizedPattern.Render(dbms, output, parameters);
            output.Append(")");
        }

        #endregion
    }
}